import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:signage/app/modules/profile/controllers/profile_controller.dart';
import 'package:signage/app/utils/http_client.dart';
import 'package:signage/app/utils/sp_util.dart';
import 'package:signage/app/utils/toast_utils.dart';
import 'package:signage/l10n/l10n.dart';
import 'package:signage/widgets/edit_dialog.dart';
import 'package:signage/widgets/phone_edit_dialog.dart';

class EditInfoController extends GetxController {
  final ImagePicker _picker = ImagePicker();
  final HttpClient httpClient = HttpClient();
  //TODO: Implement EditInfoController
  final ProfileController profileController = Get.find<ProfileController>();
  final count = 0.obs;
  final token = ''.obs;
  @override
  void onInit() async {
    super.onInit();
    token.value = SpUtil.getString('token') ?? '';
    print('token: $token');
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void increment() => count.value++;

  void showImagePicker() {
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Padding(
              padding: EdgeInsets.symmetric(vertical: 16),
              child: Text(
                AppLocalizations.of(Get.context!)!.translate('change_avatar'),
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            ListTile(
              title: Text(
                AppLocalizations.of(Get.context!)!.translate('choose_from_gallery'),
                style: TextStyle(fontSize: 16),
                textAlign: TextAlign.center
              ),
              onTap: () async {
                Get.back();
                final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
                if (image != null) {
                  updateFile(image.path);
                }
              },
            ),
            ListTile(
              title: Text(
                AppLocalizations.of(Get.context!)!.translate('take_photo'),
                style: TextStyle(fontSize: 16),
                textAlign: TextAlign.center
              ),
              onTap: () async {
                Get.back();
                final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
                if (photo != null) {
                  updateFile(photo.path);
                }
              },
            ),
            ListTile(
              title: Center(child: Text(AppLocalizations.of(Get.context!)!.translate('cancel'))),
              onTap: () => Get.back(),
            ),
          ],
        ),
      ),
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
      ),
    );
  }

  void updateFile(String imagePath) async {
    final file = File(imagePath);
    final response = await httpClient.uploadFile(file: file);
    if (response.code == 200) {
      final id = response.fileInfo!.id;
      final url = '${HttpClient.baseUrl}/api/base/file/$id/download';
      final file = await httpClient.updateAvatar(avatarUrl: url);
      if (file.code == 200) {
        profileController.getUserInfo();
        ToastUtils.show(AppLocalizations.of(Get.context!)!.translate('update_avatar_success'));
      }
    }
  }

  void editName() {
    final controller = TextEditingController(text: profileController.userInfo.value.name);
    Get.dialog(
      EditDialog(
        controller: controller,
        title: AppLocalizations.of(Get.context!)!.translate('edit_nickname'),
        hintText: AppLocalizations.of(Get.context!)!.translate('enter_nickname'),
        onConfirm: () async {
          if (controller.text.isEmpty) {
            ToastUtils.show(AppLocalizations.of(Get.context!)!.translate('nickname_empty'));
            return;
          }
          Get.back();
          final response = await httpClient.updateDisplayName(name: controller.text);
          if (response.code == 200) {
            profileController.getUserInfo();
            ToastUtils.show(AppLocalizations.of(Get.context!)!.translate('update_nickname_success'));
          }
        },
      ),
    );
  }

  void editMobile() {
    final phoneController = TextEditingController();
    final codeController = TextEditingController();

    Get.dialog(
      PhoneEditDialog(
        phoneController: phoneController,
        codeController: codeController,
        onGetCode: () {
          // 处理获取验证码逻辑
        },
        onConfirm: () async {
          try {
            final response = await httpClient.changeMobile(
              mobile: phoneController.text,
              captcha: codeController.text,
            );
            if (response.code == 200) {
              profileController.getUserInfo();
              ToastUtils.show(AppLocalizations.of(Get.context!)!.translate('update_mobile_success'));
            } else {
              ToastUtils.show(response.msg ?? AppLocalizations.of(Get.context!)!.translate('update_mobile_failed'));
            }
          } catch (e) {
            ToastUtils.show(AppLocalizations.of(Get.context!)!.translate('update_mobile_failed'));
          }
          Get.back();
        },
      ),
    );
  }
}
